package com;

import com.exception.UnsupportedTypeException;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

public class SimpleBeanConvertor {
    public static <T> T convert(HttpServletRequest request,Class<T> targetType) throws IllegalAccessException, InstantiationException, InvocationTargetException, UnsupportedTypeException {
        //获取所有请求参数
        Map<String, String[]> params = request.getParameterMap();
        if (params.size() == 0) {
            return null;
        }
        T target = targetType.newInstance();    //创建JavaBean实例
        //获取JavaBean中的所有方法
        Method[] allMethods = targetType.getMethods();
        if (allMethods != null && allMethods.length > 0) {
            for (Method method : allMethods) {
                if (method.getName().startsWith("set")) { //仅处理setter访问器
                    Class[] args = method.getParameterTypes(); //获取参数列表
                    if (args.length == 1) {//仅处理单参情况
                        //获取set方法中对应的请求参数 setName 》 name
                        String paramName = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
                        if (params.containsKey(paramName)) { //请求中有此参数
                            try { //将请求参数值转换为setter方法参数类型
                                Object value = parseValue(params.get(paramName), args[0]);
                                method.invoke(target, value);
                            } catch (ParseException e) {
                                e.printStackTrace();
                                System.out.println("参数转换错误");
                            }
                        } else if (Boolean.class == args[0] || boolean.class == args[0]) {
                            //如果是boolean 不存在表示false
                            method.invoke(target, false);
                        }
                    }
                }
            }
        }
        return target;
    }

    private static Object parseValue(String [] value , Class type) throws ParseException, UnsupportedTypeException {
        if (String.class == type) {
            return value[0];
        }
        if (java.util.Date.class == type) {
            return new SimpleDateFormat("yyyy-MM-dd").parse(value[0]);
        }
        if (boolean.class == type || Boolean.class == type) {
            return true;
        }
        if (char.class == type || Character.class == type) {
            return value[0].charAt(0);
        }
        if (int.class == type || Integer.class == type) {
            return Integer.valueOf(value[0]);
        }
        if (short.class == type || byte.class == type || long.class == type || float.class == type || double.class == type) {
            try {
                //将值类型变更为对应的包装类型
                type = Class.forName("java.lang." + type.getName().substring(0, 1).toUpperCase() + type.getName().substring(1));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (type.getName().startsWith("java.lang") || type.getName().startsWith("java.math")) {
            try {
                return type.getConstructor(String.class).newInstance(value[0]);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        if(type.isArray()){
            String[] str=(String[])java.lang.reflect.Array.newInstance(String[].class.getComponentType(),value.length);
            for (int i = 0; i <str.length ; i++) {
                str[i]=value[i];
            }
            return str;
        }
        throw new UnsupportedTypeException();
    }
}
